package com.wind.test;

import com.wind.entity.Customer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.List;

public class JpaTest08_JPQL_关联查询 {

  private EntityManagerFactory entityManagerFactory;
  private EntityManager entityManager;
  private EntityTransaction entityTransaction;

  @Before
  public void init() {
    entityManagerFactory = Persistence.createEntityManagerFactory("JpaDemo");
    entityManager = entityManagerFactory.createEntityManager();
    entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();
  }

  @After
  public void destory() {
    entityTransaction.commit();
    entityManager.close();
    entityManagerFactory.close();
  }

  /*
    JPQL 关联查询 同 HQL 的关联查询
   */
  @Test
  public void testJoinFetch() {
    String jpql = "FROM Customer c LEFT JOIN FETCH c.orders WHERE c.id = ?";
    Customer customer = (Customer) entityManager.createQuery(jpql).setParameter(new Integer(1), 2).getSingleResult();
    System.out.println(customer.getCustomerName());
    System.out.println(customer.getOrders().size());
  }

  /*
    FETCH 属性去掉的话 会返回 List<Object[]> 这个结果处理起来会很麻烦~！
    建议：关联查询 一定一定 加上 FETCH 属性~！
   */
  @Test
  public void testJoin() {
    String jpql = "FROM Customer c LEFT JOIN c.orders WHERE c.id = ?";
    List<Object[]> resultList = entityManager.createQuery(jpql).setParameter(new Integer(1), 2).getResultList();
    System.out.println(resultList);
  }
}
